package cbfg.rvadapter.demo.select_multi

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import cbfg.rvadapter.RVAdapter
import cbfg.rvadapter.demo.databinding.FragmentListSelectMultiBinding
import cbfg.rvadapter.entity.RankItem
import cbfg.rvadapter.selection.SelectionDelegate
import cbfg.rvadapter.selection.store.SortType

class MultiSelectFragment : Fragment() {
    private var _binding: FragmentListSelectMultiBinding? = null
    private val binding: FragmentListSelectMultiBinding
        get() = _binding!!

    private lateinit var adapter: RVAdapter<RankItem>

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentListSelectMultiBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        adapter = RVAdapter<RankItem>(
            context = view.context,
            rvHolderFactory = MultiSelectVHFactory(),
            selectionDelegate = SelectionDelegate(
                multiSelectableArray = arrayOf(RankItem::class.java),
                enableSelectable = true,
                strictCheckDataType = false,
                sort = SortType.ItemSort(Comparator<RankItem> { o1, o2 ->
                    o1.id - o2.id
                })
            )
        ).bind(binding.rvTest)
            .setItems(getItems())
            .setItemClickListener { _, item, position ->
                adapter.toggleSelect(item, position)
                showSelectedItems()
            }

        binding.cbToggleSelectAll.setOnCheckedChangeListener { _, isChecked ->
            binding.cbToggleSelectAll.text = if (isChecked) "全不选" else "全选"
        }
        binding.cbToggleSelectAll.setOnClickListener {
            if (binding.cbToggleSelectAll.isChecked) {
                adapter.selectAll()
            } else {
                adapter.deselectAll()
            }
            showSelectedItems()
        }
    }

    private fun showSelectedItems() {
        binding.tvSelections.text = "选中的项: "
        adapter.getSelections().forEach { binding.tvSelections.append("rank-${it.rank},") }
        binding.cbToggleSelectAll.isChecked = adapter.getSelections().size == adapter.itemCount
    }

    private fun getItems(): List<RankItem> {
        val items = ArrayList<RankItem>()
        for (i in 1..26) {
            items.add(RankItem(i, i))
        }
        return items
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}
